﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Automation.Provider;
using System.Windows.Automation.Peers;
using System.Text.RegularExpressions;

namespace wallstreet
{
    public partial class Control_MyStocks_View : PhoneApplicationPage
    {
        #region Info
        //http://ichart.finance.yahoo.com/table.csv?s=o&a=01&b=01&c=2010&d=02&e=01&f=2010&g=d&ignore=.csv
        //http://www.codeproject.com/KB/aspnet/StockQuote.aspx
        //http://finance.yahoo.com/q?s=STO
        //http://www.eggheadcafe.com/tutorials/aspnet/f651bcc7-1256-4e4d-bbc1-95f88500d86b/c-net-yahoo-stock-downl.aspx
        #endregion

        public Control_MyStocks_View()
        {
            InitializeComponent();

            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);

            loadStock();
            loadNews();
            loadChart();
        }

        void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void btnBack_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.GoBack();
        }

        #region Stock

            private void loadStock()
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("SelectedStock"))
                {
                    StockInfo selectedStock = IsolatedStorageSettings.ApplicationSettings["SelectedStock"] as StockInfo;

                    lblHeader.Text = selectedStock.Company;

                    string url = "http://download.finance.yahoo.com/d/quotes.csv?s="
                                 + selectedStock.Symbol
                                 + "&f="
                                 + "n"      //Name
                                 + "s"      //Symbol
                                 + "x"      //Stock Exchange
                                 + "l1"     //Last Trade (Price Only)
                                 + "t1"     //Trade Date
                                 + "c1"     //Change
                                 + "p2"     //Change in Percent
                                 + "p"      //Previous Close
                                 + "o"      //Open
                                 + "b"      //Bid
                                 + "b6"     //Bid size
                                 + "a"      //Ask
                                 + "a5"     //Ask size
                                 + "m"      //Day’s Range
                                 + "w"      //52-week Range
                                 + "a2"     //Average Daily Volume
                                 + "j1"     //Market Cap
                                 + "r";     //P/E (ttm)


                    WebClient client = new WebClient();
                    client.DownloadStringCompleted += ReadStock;
                    client.DownloadStringAsync(new Uri(url));
                }
            }

            private void ReadStock(object Sender, DownloadStringCompletedEventArgs e)
            {
                List<StockDetails> stockDetailsList = new List<StockDetails>();

                using (StringReader reader = new StringReader(e.Result))
                {
                    string stock;
                    while ((stock = reader.ReadLine()) != null)
                    {
                        stock = stock.Replace("\"", "");
                        string[] values = stock.Split(',');

                        string stockExchange = values[2];
                        stockExchange = stockExchange.Replace("NasdaqNM", "Nasdaq");

                        //stockDetailsList.Add(new StockDetails { Type = "Company", Value = values[0] });
                        stockDetailsList.Add(new StockDetails { Type = "Symbol", Value = values[1] });
                        stockDetailsList.Add(new StockDetails { Type = "Stock Exchange", Value = stockExchange });
                        stockDetailsList.Add(new StockDetails { Type = "Last Trade", Value = values[3] });
                        stockDetailsList.Add(new StockDetails { Type = "Change", Value = values[5] + " (" + values[6] + ")" });
                        stockDetailsList.Add(new StockDetails { Type = "Previous Close", Value = values[7] });
                        stockDetailsList.Add(new StockDetails { Type = "Open", Value = values[8] });
                        stockDetailsList.Add(new StockDetails { Type = "Bid", Value = values[9] + " x " + values[10] });
                        stockDetailsList.Add(new StockDetails { Type = "Ask", Value = values[11] + " x " + values[12] });
                        stockDetailsList.Add(new StockDetails { Type = "Day’s Range", Value = values[13] });
                        stockDetailsList.Add(new StockDetails { Type = "52-week Range", Value = values[14] });
                        stockDetailsList.Add(new StockDetails { Type = "Average Daily Volume", Value = values[15] });
                        stockDetailsList.Add(new StockDetails { Type = "Market Cap", Value = values[16] });
                        stockDetailsList.Add(new StockDetails { Type = "P/E (ttm)", Value = values[17] });
                    }
                }

                lboStock.ItemsSource = stockDetailsList;
            }

        #endregion

        #region News

            private void loadNews()
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("SelectedStock"))
                {
                    StockInfo selectedStock = IsolatedStorageSettings.ApplicationSettings["SelectedStock"] as StockInfo;

                    WebClient client = new WebClient();
                    client.DownloadStringCompleted += ReadNews;
                    client.DownloadStringAsync(new Uri(("http://finance.yahoo.com/rss/headline?s=" + selectedStock.Symbol)));
                }
            }

            private void ReadNews(object Sender, DownloadStringCompletedEventArgs e)
            {
                List<NewsFeed> newsList = new List<NewsFeed>();

                try
                {
                    if (!e.Cancelled)
                    {
                        XElement xml = XElement.Parse(e.Result);
                        foreach (XElement value in xml.Elements("channel").Elements("item"))
                        {
                            newsList.Add(new NewsFeed
                            {
                                Title = value.Element("title").Value,
                                Description = Regex.Replace(value.Element("description").Value, @"<(.|\n)*?>", String.Empty),
                                Link = value.Element("link").Value,
                                Guid = value.Element("guid").Value,
                                Published = value.Element("pubDate").Value
                            });
                        }

                        newsList.Add(new NewsFeed { Title = "" });

                        lboNews.ItemsSource = newsList;
                        lblLoading.Visibility = Visibility.Collapsed;
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString());
                }
            }

            private void lboNews_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                NewsFeed feed = lboNews.SelectedItem as NewsFeed;

                if (feed != null && feed.Link != "")
                {
                    if (IsolatedStorageSettings.ApplicationSettings.Contains("NewsFeed"))
                        IsolatedStorageSettings.ApplicationSettings["NewsFeed"] = feed;
                    else
                        IsolatedStorageSettings.ApplicationSettings.Add("NewsFeed", feed);

                    if (feed != null)
                    {
                        // Create a ButtonAutomationPeer using the ClickButton
                        ButtonAutomationPeer buttonAutoPeer = new ButtonAutomationPeer(btnCommand);
                        // Create an InvokeProvider
                        IInvokeProvider invokeProvider = buttonAutoPeer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
                        // Invoke the default event, which is click for the button
                        invokeProvider.Invoke();
                    }

                    lboNews.SelectedIndex = -1;
                }
            }

            private void btnCommand_Click(object sender, RoutedEventArgs e)
            {
                this.NavigationService.Navigate(new Uri("/Control_News_View.xaml", UriKind.Relative));
            }

        #endregion

        #region Chart

            private void loadChart()
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("SelectedStock"))
                {
                    StockInfo selectedStock = IsolatedStorageSettings.ApplicationSettings["SelectedStock"] as StockInfo;

                    DateTime thisMonth = DateTime.Now;
                    DateTime lastMonth = thisMonth.AddMonths(-1);

                    //http://ichart.finance.yahoo.com/table.csv?s=sto&a=09&b=1&c=1998&d=08&e=7&f=2010&g=d&ignore=.csv
                    //http://ichart.finance.yahoo.com/table.csv?s=sto&a=09&b=6&c=2010&d=10&e=6&f=2010&g=d&ignore=.csv
                    //http://ichart.finance.yahoo.com/table.csv?s=MSFT&a=9&b=6&c=2010&d=10&e=6&f=2010&g=d&ignore=.csv

                    string url = "" +
                                 "http://ichart.finance.yahoo.com/table.csv?s=" +
                                 selectedStock.Symbol +
                                 "&a=" + (lastMonth.Month -1) + 
                                 "&b=" + lastMonth.Day + 
                                 "&c=" + lastMonth.Year +
                                 "&d=" + thisMonth.Month +
                                 "&e=" + thisMonth.Day +
                                 "&f=" + thisMonth.Year +
                                 "&g=d" + 
                                 "&ignore=.csv";

                    WebClient client = new WebClient();
                    client.DownloadStringCompleted += ReadChart;
                    client.DownloadStringAsync(new Uri((url)));
                }
            }

            private void ReadChart(object Sender, DownloadStringCompletedEventArgs e)
            {
                ObservableCollection<StockDetails> stockDatas = new ObservableCollection<StockDetails>();

                using (StringReader reader = new StringReader(e.Result))
                {
                    string stock;
                    while ((stock = reader.ReadLine()) != null)
                    {
                        stock = stock.Replace("\"", "");
                        string[] values = stock.Split(',');

                        if (!values[0].Equals("Date"))
                        {
                            stockDatas.Add(new StockDetails { Close = Convert.ToDouble(values[4]), Date = Convert.ToDateTime(values[0]) });
                        }
                    }
                }

                Dispatcher.BeginInvoke(() => this.Chart1.DataContext = stockDatas);
            }

        #endregion
    }

    public class StockDetails
    {
        public string Type { get; set; }
        public string Value { get; set; }

        public double Close { get; set; }
        public DateTime Date { get; set; }
    }
}